package com.rxyl.love.petdoctor.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.rxyl.love.petdoctor.R;
import com.rxyl.love.petdoctor.acticity.CityActivity;
import com.rxyl.love.petdoctor.acticity.DoctorDetailActivity;
import com.rxyl.love.petdoctor.acticity.HospitalActivity;
import com.rxyl.love.petdoctor.acticity.MainActivity;
import com.rxyl.love.petdoctor.acticity.SearchActivity;
import com.rxyl.love.petdoctor.adapter.BannerListAdapter;
import com.rxyl.love.petdoctor.adapter.MyGridViewAdapter;
import com.rxyl.love.petdoctor.adapter.MyListViewAdapter;
import com.rxyl.love.petdoctor.constant.Urls;
import com.rxyl.love.petdoctor.entity.Banner;
import com.rxyl.love.petdoctor.entity.CityEntity;
import com.rxyl.love.petdoctor.entity.GoodDoctor;
import com.rxyl.love.petdoctor.entity.KeyWord;
import com.rxyl.love.petdoctor.entity.NearbyHospital;
import com.rxyl.love.petdoctor.util.NetworkUtil;
import com.rxyl.love.petdoctor.util.SharedUtil;
import com.rxyl.love.petdoctor.acticity.MainWebActivity;
import com.rxyl.love.petdoctor.view.MyListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 * Created by Administrator on 2016/1/9 0009.
 */
public class MainFragment extends Fragment implements ViewPager.OnPageChangeListener {

    @ViewInject(R.id.btn_showSlidingMenu)
    private SimpleDraweeView btn_show;

    @ViewInject(R.id.vp_main_fragment)
    private ViewPager viewPager;

    @ViewInject(R.id.ll_point)
    private LinearLayout mLLPoint;

    @ViewInject(R.id.ll_keywords)
    private LinearLayout mKeyWords;

    @ViewInject(R.id.gridView_main)
    private GridView gridView;

    @ViewInject(R.id.listView_main)
    private MyListView listView;

    @ViewInject(R.id.tv_main_search)
    private TextView tv_search;

    @ViewInject(R.id.city_selector)
    private TextView city_name;

    @ViewInject(R.id.ll_dog)
    private LinearLayout ll_dog;

    @ViewInject(R.id.ll_cat)
    private LinearLayout ll_cat;

    private BannerListAdapter mAdapter;
    private MyListViewAdapter lvAdapter;
    private MyGridViewAdapter gvAdapter;

    //导航数据的加载
    private List<Banner.DataEntity> mBanners;
    //宠物好医生的数据加载
    private List<GoodDoctor.DataEntity> goodDoctorList;
    //周边医院的数据加载
    private List<NearbyHospital.DataEntity> nearbyHospitalList;
    //关键词的数据加载
    private List<KeyWord.DataEntity> keyWordList;
    //导航中的点
    private List<ImageView> mImageViews;

    private MainActivity mainActivity;

    private String cityName = "北京";
    private ImageView mCurrentImageView;
    private int currentPageNO = 0;
    private int docId;
    private int hosId;

    public static final int REQUEST_CITY = 0x001;
    public static final int RESULT_CITY = 0x002;
    public static final int RESULT_STRING = 0x003;

    //关键词的背景颜色图形
    private int[] bgColor = {R.drawable.shape_keyword_1, R.drawable.shape_keyword_2
            , R.drawable.shape_keyword_3, R.drawable.shape_keyword_4
            , R.drawable.shape_keyword_5};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_layout, container, false);
        ViewUtils.inject(this, view);
        //初始化视图
        initViews();
        loadBanner();
        addKeyWords();
        loadDocDatas();
        loadHosDatas();
        return view;
    }

    private void initViews() {
        mImageViews = new ArrayList<>();
        mBanners = new ArrayList<>();
        goodDoctorList = new ArrayList<>();
        nearbyHospitalList = new ArrayList<>();
        keyWordList = new ArrayList<>();

        mAdapter = new BannerListAdapter(getActivity(), mBanners);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(this);

        gvAdapter = new MyGridViewAdapter(getActivity(), goodDoctorList);
        gridView.setAdapter(gvAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), DoctorDetailActivity.class);
                intent.putExtra("docId", goodDoctorList.get(position).getUid());
                startActivity(intent);
            }
        });
        lvAdapter = new MyListViewAdapter(getActivity(), nearbyHospitalList);
        listView.setAdapter(lvAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), HospitalActivity.class);
                intent.putExtra("hospitalId", nearbyHospitalList.get(position).getId());
                startActivity(intent);
            }
        });

        cityName = SharedUtil.getString("cityname");
        city_name.setText(cityName);

        city_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到城市选择页面
                startActivityForResult(new Intent(getActivity(),
                        CityActivity.class), REQUEST_CITY);
            }
        });

        btn_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //点击头像显示侧边栏
                mainActivity = (MainActivity) getActivity();
                mainActivity.showSlingMenu();
            }
        });

        ll_dog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainWebActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("mainUrl", Urls.DOGCAT + "1");
                intent.putExtra("lable", "宠物狗");
                startActivity(intent);
            }
        });

        ll_cat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainWebActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("mainUrl", Urls.DOGCAT + "2");
                intent.putExtra("lable", "宠物猫");
                startActivity(intent);
            }
        });

        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }

    private void loadBanner() {
        NetworkUtil.getInstance().getBannaer(new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                Gson gson = new Gson();
                Banner banner = gson.fromJson(responseInfo.result.toString(), Banner.class);
                if (banner != null) {
                    mBanners.clear();
                    mBanners.addAll(banner.getData());

                    addPoints();

                    hanlder.sendEmptyMessageDelayed(1, 3000);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    private void addPoints() {
        if (mBanners == null || mBanners.isEmpty()) {
            return;
        }

        mImageViews.clear();

        LinearLayout.LayoutParams layoutParams =
                new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);

        layoutParams.rightMargin = 10;

        for (int i = 0; i < mBanners.size(); i++) {
            mCurrentImageView = new ImageView(getActivity());
            mCurrentImageView.setLayoutParams(layoutParams);


            mCurrentImageView.setSelected(false);

            mCurrentImageView.setImageResource(R.drawable.seletor_nav_points);

            mImageViews.add(mCurrentImageView);
            mLLPoint.addView(mCurrentImageView);
        }
        mCurrentImageView = mImageViews.get(0);
        mCurrentImageView.setSelected(true);
    }


    private void addKeyWords() {
        if (viewPager == null) {
            return;
        }

        keyWordList.clear();

        NetworkUtil.getInstance().getKeyWords(new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                Gson gson = new Gson();
                KeyWord keyWords = gson.fromJson(responseInfo.result.toString(), KeyWord.class);
                if (keyWords != null) {
                    keyWordList.addAll(keyWords.getData());
                }
                LinearLayout.LayoutParams layoutParams =
                        new LinearLayout.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.MATCH_PARENT);

                layoutParams.rightMargin = 20;
                for (int i = 0; i < keyWordList.size(); i++) {

                    TextView tv = new TextView(getActivity());
                    tv.setText(keyWordList.get(i).getName());
                    tv.setLayoutParams(layoutParams);
                    tv.setPadding(20, 25, 20, 25);
                    tv.setBackgroundResource(bgColor[i % 5]);
                    tv.setTextColor(Color.WHITE);
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                    final int finalI = i;
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), MainWebActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("mainUrl", "http://api.5ichong.com"
                                    + keyWordList.get(finalI).getLink());
                            intent.putExtra("lable", keyWordList.get(finalI).getName());
                            startActivity(intent);
                        }
                    });
                    mKeyWords.addView(tv);

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    private Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            currentPageNO = ++currentPageNO % mBanners.size();
            mCurrentImageView.setSelected(false);
            mCurrentImageView = mImageViews.get(currentPageNO);
            mCurrentImageView.setSelected(true);
            viewPager.setCurrentItem(currentPageNO);
            hanlder.sendEmptyMessageDelayed(1, 5000);
        }
    };

    private void loadDocDatas() {
        cityName = SharedUtil.getString("cityname");
        String latitude = SharedUtil.getString("latitude");
        String longitude = SharedUtil.getString("longitude");
        String url = Urls.GOOD_DOCTORS
                + "?city=" + cityName + "&latitude=" + latitude +
                "&longitude=" + longitude;
        NetworkUtil.getInstance().getGoodDoctor(url, new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                Gson gson = new Gson();
                GoodDoctor goodDoctor = gson.fromJson(responseInfo.result.toString(), GoodDoctor.class);
                if (goodDoctor != null) {
                    goodDoctorList.clear();
                    goodDoctorList.addAll(goodDoctor.getData());
                    gvAdapter.notifyDataSetChanged();
                    loadMore();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    private void loadHosDatas() {
        cityName = SharedUtil.getString("cityname");
        String latitude = SharedUtil.getString("latitude");
        String longitude = SharedUtil.getString("longitude");
        String url = Urls.NEARBY_HOSPITAL + "?city=" + cityName + "&latitude=" + latitude
                + "&region=全部&longitude=" + longitude;
        NetworkUtil.getInstance().getNearbyHospital(url, new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                Gson gson = new Gson();
                NearbyHospital nearbyHospital = gson.fromJson(responseInfo.result.toString(), NearbyHospital.class);
                if (nearbyHospital != null) {
                    nearbyHospitalList.clear();
                    nearbyHospitalList.addAll(nearbyHospital.getData());
                    lvAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });

    }

    private void loadMore() {
        if (listView.getFooterViewsCount() > 0) {
            return;
        }
        //android 4.4 必须使用AbsListView
        AbsListView.LayoutParams layoutParams =
                new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        Button btn = new Button(getActivity());
        btn.setText("查看更多");
        btn.setBackgroundColor(Color.WHITE);
        btn.setTextColor(Color.GRAY);
        btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        btn.setLayoutParams(layoutParams);
        listView.addFooterView(btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainActivity = (MainActivity) getActivity();
                mainActivity.loadMoreHospital();
            }
        });

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (mCurrentImageView == null) {
            return;
        }

        currentPageNO = position;

        mCurrentImageView.setSelected(false);
        mCurrentImageView = mImageViews.get(position);
        mCurrentImageView.setSelected(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CITY && resultCode == RESULT_CITY) {
            CityEntity cityEntity = (CityEntity) data.getSerializableExtra("citys");
            String latitude = SharedUtil.getString("latitude");
            String longitude = SharedUtil.getString("longitude");
            setCityName(cityEntity.getCity_name(), latitude, longitude);
        }
        //当前定位的城市
        if (requestCode == REQUEST_CITY && resultCode == RESULT_STRING) {
            String cityname = data.getStringExtra("city");
            String latitude = data.getStringExtra("latitude");
            String longitude = data.getStringExtra("longitude");
            setCityName(cityname, latitude, longitude);
        }

    }


    public void setCityName(String cityName, String latitude, String longitude) {
        this.cityName = cityName;
        city_name.setText(cityName);

        SharedUtil.putString("cityname", cityName);
        //TODO 当数据库建好的时候写入城市ID
        SharedUtil.putString("districtname", "全部");
        SharedUtil.putString("latitude", latitude);
        SharedUtil.putString("longitude", longitude);

        loadDocDatas();
        loadHosDatas();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // hanlder.removeMessages(1);
        hanlder.removeCallbacksAndMessages(null);
    }

}
